<?php


namespace app\common\service\companyIndustry\realtime;

use app\common\service\{
    BaseService, MongoService, CommonService, ControlService
};
use think\facade\Config;

/**
 * 钙硫比（脱硫）
 */
class SulfurCaSRatioService extends BaseService
{
    /**
     * （减排前）脱硫钙硫比
     * @@param $companyId
     * @param $drainId
     * @param $facilityId
     * @return int
     */
    public function singleCompanySingleDrainSingleFacility($facilityId)
    {
        return 1;
    }


    /**
     * （减排前）脱硫钙硫比趋势图 - 返回天数
     * @author yy by 2019/7/23
     * @param $facilityId
     * @param $plan_ca
     * @param $plan_number
     * @param string $type $type days天数| hours小时数
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function singleCompanySingleDrainSingleFacilityDetails($plan_ca,$plan_number, $facilityId, $type = 'days')
    {
        $commonService           = new CommonService();
        $list                    = [];
        $control                 = new ControlService();
        $beforeTime['start_day'] = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $beforeTime['end_day']   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';
        $mongodb_huanxin         = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document                = [
            'aggregate'    => 'company_industry_monitor_sulfur_minute',
            'pipeline'     => [
                [
                    '$project' => [
                        'facility_id'          => 1,
                        'publish_time'         => 1,
                        'time'                 => ['$substr' => ['$publish_time', 0, 10]],
                        'calcium_sulfur_ratio' => 1,
                    ],
                ],
                [
                    '$match' => [
                        'facility_id'  => (int)$facilityId,
                        'publish_time' => [
                            '$gte' => $beforeTime['start_day'],
                            '$lt' => $beforeTime['end_day'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'   => ['time' => '$time'],
                        'total' => ['$avg' => '$calcium_sulfur_ratio'],
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command                 = new \MongoDB\Driver\Command($document);
        $rows                    = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend      = json_decode(json_encode($rows, 320), true);
        $num                     = count($contribution_trend[0]['result']);
        // 日期补全
        $date_all = $commonService->getMongoDate(date('Y-m-d', strtotime($beforeTime['start_day'])), date('Y-m-d', strtotime($beforeTime['end_day'])));
        if ($num > 0) {
            for ($i = 0; $i < $num; $i++) {
                $list['date'][$i] = date('Y-m-d', strtotime($contribution_trend[0]['result'][$i]['_id']['time']));
                $list['data'][$i] = $type == 'days'
                    ? sprintf('%.3f', $contribution_trend[0]['result'][$i]['total'])
                    : sprintf('%.3f', $contribution_trend[0]['result'][$i]['total'] / 24);
            }
            # 比较差集
            $different     = array_values(array_diff($date_all, $list['date']));
            $different_num = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $list['date'][] = $different[$i];
                    $list['data'][] = '';
                }
            }
        } else {
            $list['date'] = $date_all;
            for ($i = 0; $i < count($list['date']); $i++) {
                $list['data'][$i] = '';
            }
        }
        // 依据publish_time排序
        array_multisort($list['date'], $list['data']);
        for ($m = 0; $m < count($list['date']); $m++) {
            $list['date'][$m] = date('m/d', strtotime($list['date'][$m]));
        }
        $need = $list['data'];
        unset($list['data']);
        $list['data'][0] = $plan_ca['data'][0];
        $list['data'][1] = $need;
        return $list;
    }

    /**
     * （减排前）脱硫钙硫比趋势图 - 返回天数
     * @param int $companyId
     * @param int $drainId
     * @param int $facilityId
     * @param string $type days天数| hours小时数
     * @return int
     */
    public function singleCompanySingleDrainSingleFacilityDetailsDemo($facilityId, $type = 'days')
    {
        $date   = ['07/22', '07/22', '07/22', '07/22'];
        $data   = [1, 2, 3, 4];
        $result = [
            'date' => $date,
            'data' => $data,
        ];
        return $result;
    }
}